<!-- vue模板 -->
<template>
    <div class="add-inventory-container">
        <div class="header">
            <h5>添加盘点任务</h5>
            <el-button @click="goBack" type="text" class="back-btn">
                <i class="el-icon-arrow-left"></i> 返回
            </el-button>
        </div>
        
        <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
            <el-form-item label="任务名称" prop="taskName">
                <el-input v-model="form.taskName" placeholder="请输入任务名称" maxlength="100" show-word-limit />
            </el-form-item>
            
            <el-form-item label="盘点仓库" prop="storeId">
                <el-select v-model="form.storeId" placeholder="请选择盘点仓库" @change="handleStoreChange">
                    <el-option 
                        v-for="store in storeList" 
                        :key="store.id" 
                        :label="store.name" 
                        :value="store.id" 
                    />
                </el-select>
            </el-form-item>
            
            <el-form-item label="盘点库区" prop="wareId">
                <el-select v-model="form.wareId" placeholder="请选择盘点库区" multiple @change="handleWareChange">
                    <el-option 
                        v-for="ware in wareList" 
                        :key="ware.id" 
                        :label="ware.name" 
                        :value="ware.id" 
                    />
                </el-select>
            </el-form-item>
            
            <el-form-item label="盘点货架" prop="locationId">
                <el-select v-model="form.locationId" placeholder="请选择盘点货架" multiple>
                    <el-option 
                        v-for="location in locationList" 
                        :key="location.id" 
                        :label="location.name" 
                        :value="location.id" 
                    />
                </el-select>
            </el-form-item>
            
            <el-form-item label="默认盘点人" prop="userId">
                <el-select v-model="form.userId" placeholder="请选择盘点人">
                    <el-option 
                        v-for="user in userList" 
                        :key="user.id" 
                        :label="user.name" 
                        :value="user.id" 
                    />
                </el-select>
            </el-form-item>
            
            <el-form-item label="盘点时间" prop="takeDate">
                <el-date-picker 
                    v-model="form.takeDate" 
                    type="date" 
                    placeholder="选择盘点时间"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                />
            </el-form-item>
            
            <el-form-item label="盘点备注" prop="remark">
                <el-input 
                    type="textarea" 
                    v-model="form.remark" 
                    placeholder="请输入备注" 
                    maxlength="500" 
                    show-word-limit
                    :rows="3"
                />
            </el-form-item>
            
            <el-form-item>
                <el-button type="primary">预览盘点物品</el-button>
                <el-button type="success" @click="submitForm">生成盘点任务</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<!-- 组件逻辑 -->
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { queryAllStores, queryWareAndLocByStoreId, addInventoryTask, queryUsers } from '@/api/Inventory/addTask.js'
import dayjs from 'dayjs'

const router = useRouter()
const formRef = ref()

// 表单数据
const form = reactive({
    taskName: '',
    storeId: 1,
    wareId: [],
    locationId: [],
    userId: '',
    takeDate: dayjs().format('YYYY-MM-DD'),
    remark: ''
})

// 表单验证规则
const rules = {
    taskName: [
        { required: true, message: '请输入任务名称', trigger: 'blur' },
        { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
    ],
    storeId: [
        { required: true, message: '请选择盘点仓库', trigger: 'change' }
    ],
    wareId: [
        { required: true, message: '请选择盘点库区', trigger: 'change' }
    ],
    userId: [
        { required: true, message: '请选择盘点人', trigger: 'change' }
    ],
    takeDate: [
        { required: true, message: '请选择盘点时间', trigger: 'change' }
    ]
}

// 数据列表
const storeList = ref([])
const wareList = ref([])
const locationList = ref([])
const userList = ref([])
const allWareAndLocData = ref([])

// 获取所有仓库列表
async function fetchAllStores() {
    try {
        const response = await queryAllStores()
        if (response.code === 200) {
            storeList.value = response.data.map(store => ({
                id: store.id,
                name: store.name
            }))
        } else {
            ElMessage.error('获取仓库列表失败：' + response.msg)
        }
    } catch (error) {
        ElMessage.error('获取仓库列表失败：' + error.message)
    }
}

// 仓库选择变化事件
async function handleStoreChange(storeId) {
    if (!storeId) return
    
    try {
        const response = await queryWareAndLocByStoreId(storeId)
        if (response.code === 200) {
            allWareAndLocData.value = response.data || []
            
            // 提取唯一的库区信息
            const uniqueAreas = []
            const areaMap = new Map()
            
            allWareAndLocData.value.forEach(item => {
                if (item.areaId && item.areaName && !areaMap.has(item.areaId)) {
                    areaMap.set(item.areaId, item.areaName)
                    uniqueAreas.push({
                        id: item.areaId,
                        name: item.areaName
                    })
                }
            })
            
            wareList.value = uniqueAreas
            
            // 清空货位和用户列表
            locationList.value = []
            userList.value = []
            form.wareId = []
            form.locationId = []
            form.userId = ''
            
        } else {
            ElMessage.error('获取仓库信息失败：' + response.msg)
        }
    } catch (error) {
        ElMessage.error('获取仓库信息失败：' + error.message)
    }
}

// 库区选择变化事件
function handleWareChange(wareIds) {
    if (!wareIds || wareIds.length === 0) {
        locationList.value = []
        userList.value = []
        form.locationId = []
        form.userId = ''
        return
    }
    
    // 根据选中的库区ID筛选货位
    const selectedLocations = []
    const locationMap = new Map()
    
    allWareAndLocData.value.forEach(item => {
        if (wareIds.includes(item.areaId) && item.locationId && item.locationName) {
            if (!locationMap.has(item.locationId)) {
                locationMap.set(item.locationId, item.locationName)
                selectedLocations.push({
                    id: item.locationId,
                    name: item.locationName
                })
            }
        }
    })
    
    locationList.value = selectedLocations
    
    // 加载用户列表
    loadUserList()
}

// 加载用户列表
async function loadUserList() {
    try {
        const response = await queryUsers()
        if (response.code === 200) {
            userList.value = response.data
        } else {
            ElMessage.error('获取用户列表失败：' + response.msg)
        }
    } catch (error) {
        ElMessage.error('获取用户列表失败：' + error.message)
    }
}

// 初始化数据
onMounted(() => {
    fetchAllStores()
    handleStoreChange(1)
})

// 提交表单
async function submitForm() {
    formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                // 构建后端期望的数据结构
                const submitData = {
                    taskName: form.taskName,
                    stockId: form.storeId,
                    stockName: storeList.value.find(store => store.id === form.storeId)?.name || '',
                    userId: form.userId,
                    takeDate: form.takeDate,
                    note: form.remark,
                    taskType: 0, // 0-按货位
                    areaList: buildAreaList()
                }
                
                // 验证数据结构
                if (!submitData.areaList || submitData.areaList.length === 0) {
                    ElMessage.error('请选择至少一个库区')
                    return
                }
                
                // 验证是否有货位选择
                let hasLocations = false
                submitData.areaList.forEach(area => {
                    if (area.stkLocationLocDTOList && area.stkLocationLocDTOList.length > 0) {
                        hasLocations = true
                    }
                })
                
                if (!hasLocations) {
                    ElMessage.error('请选择至少一个货位')
                    return
                }
                
                console.log('提交的数据结构:', JSON.stringify(submitData, null, 2))
                
                const response = await addInventoryTask(submitData)
                
                if (response.code === 200) {
                    ElMessage.success('盘点任务创建成功！')
                    resetForm()
                } else {
                    ElMessage.error('创建失败：' + (response.msg || '未知错误'))
                }
            } catch (error) {
                ElMessage.error('提交失败：' + (error.message || '网络错误'))
            }
        } else {
            ElMessage.error('请完善表单信息')
        }
    })
}

// 构建库区列表数据结构
function buildAreaList() {
    const areaList = []
    
    // 根据选中的库区ID构建库区列表
    if (form.wareId && form.wareId.length > 0) {
        form.wareId.forEach(wareId => {
            const area = {
                id: wareId,
                name: wareList.value.find(ware => ware.id === wareId)?.name || '',
                stkLocationLocDTOList: buildLocationListForArea(wareId)
            }
            areaList.push(area)
        })
    }
    
    return areaList
}

// 构建指定库区下的货位列表数据结构
function buildLocationListForArea(wareId) {
    const locationList = []
    
    // 根据选中的货位ID构建货位列表，只包含属于当前库区的货位
    if (form.locationId && form.locationId.length > 0) {
        form.locationId.forEach(locationId => {
            const locationData = allWareAndLocData.value.find(item => 
                item.locationId === locationId && item.areaId === wareId
            )
            
            if (locationData) {
                const locationDTO = {
                    id: locationId,
                    name: locationData.locationName
                }
                locationList.push(locationDTO)
            }
        })
    }
    
    return locationList
}

// 重置表单
function resetForm() {
    form.taskName = ''
    form.wareId = []
    form.locationId = []
    form.userId = ''
    form.takeDate = dayjs().format('YYYY-MM-DD')
    form.remark = ''
    locationList.value = []
    userList.value = []
}

// 返回上一页
function goBack() {
    router.go(-1)
}
</script>

<!-- 组件样式 -->
<style scoped>
.add-inventory-container {
    padding: 20px;
    background-color: white;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.header h5 {
    margin: 0;
    color: #303133;
}

.back-btn {
    color: #606266;
    font-size: 14px;
}

.el-form {
    max-width: 800px;
    margin-top: 20px;
}

.form-hint {
    margin-left: 10px;
    color: #909399;
    font-size: 12px;
}

.rules-section {
    margin-top: 30px;
    padding: 20px;
    background-color: #f5f7fa;
    border-radius: 4px;
}

.rules-section h6 {
    margin: 0 0 15px 0;
    color: #303133;
    font-size: 14px;
}

.rules-section ol {
    margin: 0;
    padding-left: 20px;
    color: #606266;
    line-height: 1.6;
}

.rules-section li {
    margin-bottom: 8px;
}

.el-select {
    width: 100%;
}

.el-date-picker {
    width: 100%;
}
</style>
